package Internet;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

public class UdpEchoClient {
    private DatagramSocket socket=null;
    //记录ip与端口号
    private String ServerIp;
    private int ServerPort;
    //服务器的ip与端口号
    public UdpEchoClient(String ServerIp,int ServerPort) throws SocketException {
        this.ServerIp=ServerIp;
        this.ServerPort=ServerPort;
        //客户端这里的端口号等到操作系统随机分配
        socket=new DatagramSocket();
    }
    public void start() throws IOException {
        Scanner scanner=new Scanner(System.in);
        while(true){
            System.out.println("请输入内容");
            //按ctrl+d会break
            if(!scanner.hasNext()){
                break;
            }
            //1。从控制台读取用户要输入的内容
            String resquest=scanner.next();
            //2.把请求发送给服务器
            DatagramPacket resquestPacket=new DatagramPacket(resquest.getBytes(),resquest.getBytes().length,InetAddress.getByName(ServerIp),
                    ServerPort);
//            socket.receive(resquestPacket);
            //3.发送数据包
            socket.send(resquestPacket);
            //4.接受服务器的响应
            DatagramPacket responsePacket=new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);
            //5.将服务器读取的数据进行解析，打印出来
            String response=new String(responsePacket.getData(),0,responsePacket.getLength());
            System.out.println(response);

        }
    }
    public static void main(String[] args) throws IOException {
        UdpEchoClient udpEchoClient=new UdpEchoClient("127.0.0.1",1777);
        udpEchoClient.start();


    }
}

